package com.example.pbj;


import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class Submit extends Activity {
	
	String username;
	String cat;
	String subject;
    String[] cats= {"Food" ,"Environment","Events","Misc"};
	String question;
	private static final String PHP_SUBMIT = "http://webdev.cs.uwosh.edu/students/meyers11/PHPSubmit.php";
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_submit);
		
		Spinner cat1 = (Spinner) findViewById(R.id.cat1);
		ArrayAdapter<String> a1 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, cats);
		
		a1.setDropDownViewResource(
		           android.R.layout.simple_spinner_dropdown_item);
		cat1.setAdapter(a1);
		
		findViewById(R.id.submitpost).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						new submit().execute();
					}
				});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.submit, menu);
		
		
		return true;
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		new getLoginInfo().execute();
		
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
	    // Handle item selection
	    switch (item.getItemId()) {	
	        case R.id.action_logout:
	        	new Logout().execute();
	        	Intent myIntent3 = new Intent(Submit.this, LoginActivity.class);
				startActivityForResult(myIntent3, 0);
				Submit.this.finish();
	            return true;
	        case R.id.action_home:
	        	new Logout().execute();
	        	Intent myIntent4 = new Intent(Submit.this, MainActivity.class);
				startActivityForResult(myIntent4, 0);
				Submit.this.finish();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	//Get Login Info
		private class getLoginInfo extends AsyncTask<Void, Void, String>{
			@Override
			protected String doInBackground(Void... nothing) {
				
				PBJDataSource mds2 = new PBJDataSource(Submit.this);
				
				mds2.open();
				
				try {
					username = mds2.getUsername();
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				mds2.close();
				
				return username;
			}
			
		}
		
		//Submit
		private class submit extends AsyncTask<Void, Void, String>{
			@Override
			protected String doInBackground(Void... nothing) {
				
				Spinner cat1 = (Spinner) findViewById(R.id.cat1);
				EditText subject1 = (EditText) findViewById(R.id.subjecttext);
				EditText question1 = (EditText) findViewById(R.id.questiontext);
				cat = (String) cat1.getItemAtPosition(cat1.getSelectedItemPosition());
				subject = subject1.getText().toString();
				question = question1.getText().toString();
				String response1 ="";
				
				if (subject.equals("")){
					response1 = "subject";
				}
				else if(question.equals("")){
					response1 = "question";
				}
				else{
				// TODO: attempt authentication against a network service.
				String response = "";
				ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
				
				if(networkInfo != null && networkInfo.isConnected())
				{
					
					ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
					n.add(new BasicNameValuePair("cat", cat));
					n.add(new BasicNameValuePair("submitter", username));
					n.add(new BasicNameValuePair("subject", subject));
					n.add(new BasicNameValuePair("question", question));
					
					HttpClient httpClient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost(PHP_SUBMIT);
					try
					{
						httppost.setEntity(new UrlEncodedFormEntity(n));
						ResponseHandler<String> respondHandler = new BasicResponseHandler();
						response = httpClient.execute(httppost, respondHandler);
					}
					catch(Exception e){
						System.out.println("HELLO submit connection error: " + e);
						
					}
				}
				}
				
				return response1;
			}
			
			@Override
			protected void onPostExecute(String whatever) {
				if(whatever.equals("subject")){
					Context context = getApplicationContext();
					Toast.makeText(context, "Must enter a Subject", Toast.LENGTH_SHORT).show();
				}
				else if(whatever.equals("question")){
					Context context = getApplicationContext();
					Toast.makeText(context, "Must enter a Question", Toast.LENGTH_SHORT).show();
				}
				else{
					Intent myIntent = new Intent(Submit.this, MyPosts.class);
					startActivityForResult(myIntent, 0);
					Submit.this.finish();
				}
			}
			
		}
		
		//Logout
		private class Logout extends AsyncTask<Void, Void, String>{
			@Override
			protected String doInBackground(Void... nothing) {
				
				PBJDataSource mds2 = new PBJDataSource(Submit.this);
				
				mds2.open();
				
				try {
					mds2.logoutUser();
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				mds2.close();
				
				return "";
			}
			
			@Override
			protected void onPostExecute(String whatever) {
					Intent myIntent = new Intent(Submit.this, LoginActivity.class);
					startActivityForResult(myIntent, 0);
					Submit.this.finish();
			}
			
		}

}
